package com.yang.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.yang.config.AlipayConfig;
import com.yang.config.NoteListConfig;
import com.yang.entity.Deposit;
import com.yang.entity.NoteOrder;
import com.yang.entity.NoteUser;
import com.yang.entity.UserNoteInfo;
import com.yang.service.DepositService;
import com.yang.service.NoteOrderService;
import com.yang.service.NoteUserService;
import com.yang.service.UserNoteInfoService;
import com.yang.utils.AliPayUtils;
import com.yang.utils.UtilsFactory;
import com.yang.utils.info.NoteResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 订单表(NoteOrder)表控制层
 *
 * @author yangdacheng
 * @since 2022-03-02 19:11:02
 */
@RestController
@RequestMapping("noteOrder")
@Slf4j
public class NoteOrderController {
    /**
     * 服务对象
     */
    @Resource
    private NoteOrderService noteOrderService;
    @Resource
    private DepositService depositService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private NoteUserService noteUserService;
    @Resource
    private UserNoteInfoService noteInfoService;
    @Resource
    private NoteListConfig noteListConfig;
    @Resource
    private UtilsFactory utilsFactory;
    @Resource
    private AliPayUtils aliPayUtils;
    @Resource
    private AlipayConfig alipayConfig;

    /**
     * 用户充值
     *
     * @param noteOrder
     * @return
     */
    @PostMapping("/addSmsResidue")
    public String addSmsResidue(NoteOrder noteOrder) {
        String payFrom = "";
        noteOrder.setOrderId(utilsFactory.buildID()).setDepositTime(new Date());
        log.info("noteOrder" + noteOrder);
        redisTemplate.opsForValue().set(noteOrder.getOrderId(), JSONObject.toJSONString(noteOrder), 10 * 60, TimeUnit.SECONDS); //存放到缓存中
        Deposit deposit = depositService.queryDepositByID(noteOrder.getDepositId());//获取充值对象
        payFrom = aliPayUtils.payInPC(noteOrder.getOrderId(),
                String.valueOf(deposit.getDepositMoney()),
                "["+noteListConfig.getAppTitle()+":短信充值]"+deposit.getDepositMoney() + "元/" + deposit.getDepositNumber() + "条",
                "提交订单时间:" + noteOrder.getDepositTime()); //获取充值表单
        return payFrom;
    }

    /**
     * 回调
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/residueReBack")
    public NoteResponseInfo residueReBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Boolean updResult = false; //用户存放用户短信修改添加后的结果
        response.setContentType("type=text/html;charset=UTF-8");
        log.info("支付宝回掉函数被调用");
        if (!alipayConfig.checkSign(request)) {
            log.info("验签失败");
            response.getWriter().write("failure");
            return new NoteResponseInfo(500, "验签失败", null);
        }
        Map<String, String> params = alipayConfig.getParams(request); //获取回调参数
        NoteOrder noteOrder = JSON.parseObject((String) redisTemplate.opsForValue().getAndDelete(params.get("out_trade_no")), NoteOrder.class);
        assert noteOrder != null;
        NoteUser noteUser = noteUserService.queryUserByID(noteOrder.getUserid());//获取用户信息
        noteUser.setUserRole(noteUser.getNoteRole().getRoleName()); //设置角色信息
        Boolean insertResult = noteOrderService.insertNoteOrder(noteOrder);
        //修改用户剩余的数量
        UserNoteInfo userNoteInfo = noteInfoService.queryUserNoteByUid(noteUser.getUserid()); //获取用户对象
        Deposit deposit = depositService.queryDepositByID(noteOrder.getDepositId());//获取用户选择的充值服务
        if (userNoteInfo != null){
            //用户存在执行修改操作
            userNoteInfo.setNoteResidue(userNoteInfo.getNoteResidue() + deposit.getDepositNumber()); //用户充值
            updResult = noteInfoService.updateUserNote(userNoteInfo);
        }else{
            //用户不存在执行添加操作
            userNoteInfo = new UserNoteInfo();
            userNoteInfo.setNoteId(utilsFactory.buildID()).setUserid(noteUser.getUserid()).setNoteResidue(deposit.getDepositNumber());
            updResult = noteInfoService.insertUserNote(userNoteInfo);
        }

        if ((insertResult != null && insertResult) && (updResult != null && updResult)) {
            return new NoteResponseInfo(200, "添加成功", noteUser);
        }
        return new NoteResponseInfo(200, "添加订单失败", null);
    }
}